<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button
						type="warning"
						:loading="exportLoading"
						icon="el-icon-upload2"
						size="small"
						class="item-gap"
						@click="onExportExcel"
					>导出</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :clearable="false" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-select v-model="searchParams.groupId" clearable :option-list="groupList" placeholder="班组" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<div class="search-bar-item-size2 item-gap">
						<el-date-picker v-model="searchParams.yearMonth" :clearable="false" size="small" style="width: 100%;" type="month" value-format="yyyy-MM" placeholder="月" />
					</div>
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="frontGroupSalaryMonthReportTable"
				show-footer
				:loading="tableLoading"
				:span-method="mergeColMethod"
				:footer-method="footerMethod"
				border
				:stripe="false"
				:data="tableData"
				:height="tableHeight + 30"
			>
				<vxe-column
					v-for="(columnItem, columnIndex) in tableColumnList"
					:key="columnIndex"
					:title="columnItem.value"
					:align="columnItem.align"
					:field="columnItem.key"
					:sortable="columnItem.sortable"
					:fixed="columnItem.fixed ? columnItem.fixed : ''"
					:min-width="columnItem.minWidth"
					:width="columnItem.width"
				>
					<template slot-scope="scope">
						<span v-if="columnItem.key === 'code'">{{ scope.row.code }}</span>
						<span v-else>{{ scope.row[scope.column.property] }}</span>
					</template>
				</vxe-column>
			</jk-table>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import XEUtils from 'xe-utils';
    import { personnelGroupPage } from '../../../api/personnel/group';
    import { spinReportAfterPlanGroupYieldReportMonth } from '../../../api/production/reports';
    export default {
        name: 'XsGroupSalaryMonthReport',
        components: {},
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': spinReportAfterPlanGroupYieldReportMonth
                },
                totalData: {
                    totalOutputM: 0,
                    totalOutputKg: 0
                },
                groupList: [],
                processList: [],
                tableData: [],
                dataId: null,
                workshopList: [],
                tableLoading: true,
                exportLoading: false,
                count: 0,
                searchParams: {
                    groupId: null,
                    yearMonth: '',
                    workshopId: null
                }
            };
        },
        mounted() {
            this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.getDependentData();
        },
        methods: {
            onWorkshopChange() {
                this.$set(this.searchParams, 'groupId', null);
                this.tableData = [];
                this.getGroupListRequest();
            },
            onExportExcel() {
                this.exportLoading = true;
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                if (params.yearMonth) {
                    params.year = new Date(params.yearMonth).getFullYear();
                    params.month = new Date(params.yearMonth).getMonth() + 1;
                }
                this.apiItem.page(params).then(res => {
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const titleList = this.tableColumnList.map(x => x.value);
                            const keyList = this.tableColumnList.map(x => x.key);
                            const dataList = res.data.res.tableData ? res.data.res.tableData : [];
                            // 合计项
                            const totalItem = {};
                            keyList.forEach((x, idx) => {
                                totalItem[x] = this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
                            });
                            dataList.push(totalItem);
                            const data = dataList.map(v => keyList.map(j => v[j]));
                            excel.export_json_to_excel({
                                header: titleList,
                                data,
                                filename: `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                    this.exportLoading = false;
                });
            },
            footerMethod({ columns, data }) {
                return [
                    columns.map((column, columnIndex) => {
                        if (columnIndex === 0) {
                            return `合计: `;
                        }
                        if (column.property !== 'belongDate') {
                            return XEUtils.sum(data, column.property);
                        }
                        return null;
                    })
                ];
            },
            mergeColMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'belongDate') {
                    if (prevRow && prevRow.belongDate === row.belongDate) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.belongDate === row.belongDate) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getGroupListRequest() {
                if (this.searchParams.workshopId) {
                    return personnelGroupPage({
                        workshopId: this.searchParams.workshopId,
                        auditState: 1
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.groupList = res.data.res;
                        }
                    });
                }
            },
            async getDependentData() {
                this.tableLoading = true;
                this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                await this.getGroupListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                if (this.searchParams.workshopId && this.searchParams.yearMonth) {
                    this.tableLoading = true;
                    const params = { ...this.searchParams };
                    if (params.yearMonth) {
                        params.year = new Date(params.yearMonth).getFullYear();
                        params.month = new Date(params.yearMonth).getMonth() + 1;
                    }
                    return this.apiItem['page'](params).then(res => {
                        this.tableLoading = false;
                        this.count = res.data.count;
                        if (res.data.status === 200) {
                            this.tableColumnList = res.data.res.tableHeader ? res.data.res.tableHeader.map(x => {
                                x.value = x.value + '';
                                if (x.key === 'empName') {
                                    x.width = 120;
                                    x.align = 'left';
                                    x.fixed = 'left';
                                } else if (x.key === 'empTotalSalary') {
                                    x.width = 150;
                                    x.align = 'right';
                                } else {
                                    x.width = 80;
                                    x.align = 'right';
                                }
                                return x;
                            }) : [];
                            this.tableData = res.data.res.tableData ? res.data.res.tableData.map(x => {
                                return x;
                            }) : [];
                            this.totalData = res.data.res.total;
                            this.$nextTick(() => {
                                // 修复底部每月1号合计计算错误的问题
                                this.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.updateData();
                            });
                        }
                    });
                }
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                if (this.searchParams.workshopId && this.searchParams.yearMonth) {
                    this.getListRequest();
                } else {
                    tipsBar(this, 'custom', 'warning', '区域、年月不能为空!');
                }
            }
        }
    };
</script>
<style>
</style>
